<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" inline v-show="showSearch">
          <el-form-item label="试卷名称" prop="paperName">
            <el-input
              v-model="queryParams.paperName"
              placeholder="请输入试卷名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="table-tools mb8">
          <div>
            <el-button type="primary" plain icon="Plus" @click="handCombine"
              >手动组卷</el-button
            >
            <el-button type="info" plain icon="Plus" @click="handleAutoCombine"
              >自动组卷</el-button
            >
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              >修改</el-button
            >
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              >删除</el-button
            >
          </div>
          <div>
            <right-toolbar
              v-model:showSearch="showSearch"
              @queryTable="getList"
            />
          </div>
        </div>

        <el-table
          v-loading="loading"
          :data="paperList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="编号" prop="id" width="50" align="center" />
          <el-table-column
            label="学科"
            align="center"
            key="subjectName"
            prop="subjectName"
            show-overflow-tooltip
          />
          <el-table-column
            label="试卷名称"
            align="center"
            key="paperName"
            prop="paperName"
            show-overflow-tooltip
          />
          <el-table-column label="参考班级" align="center">
            <template #default="scope">
              <span>{{
                scope.row.classInfoList.map((item) => item.className).toString()
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="考试时长" align="center">
            <template #default="scope">
              <span>{{ scope.row.duration }}分钟</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="creatTime"
            width="160"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                type="primary"
                link
                icon="Edit"
                @click="handleEditTest(scope.row)"
                >编辑
              </el-button>
              <el-button
                type="primary"
                link
                icon="Delete"
                @click="handleDelete(scope.row)"
                >删除
              </el-button>
              <el-button
                type="primary"
                link
                icon="download"
                @click="handleDownload(scope.row)"
                >导出
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 自动组卷对话框 -->
    <el-dialog title="自动组卷" v-model="open" width="800px" append-to-body>
      <el-form :model="form" :rules="rules" ref="combineRef" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="学科" prop="subId">
              <el-select
                v-model="form.subId"
                placeholder="请选择"
                style="width: 100%"
                @change="subjectChange"
              >
                <el-option
                  v-for="item in subjectOptions"
                  :key="item.id"
                  :label="item.subject"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="知识点" prop="knowledgeId">
              <el-select
                v-model="form.knowledgeId"
                placeholder="请选择"
                style="width: 100%"
                multiple
              >
                <el-option
                  v-for="item in knowledgeOptions"
                  :key="item.id"
                  :label="item.knowledge"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参试班级" prop="classIdList">
              <el-select
                v-model="form.classIdList"
                placeholder="请选择"
                style="width: 100%"
                multiple
              >
                <el-option
                  v-for="item in classList"
                  :key="item.id"
                  :label="item.className"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="建议时长" prop="duration">
              <el-input-number
                v-model="form.duration"
                min="1"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              v-for="item in form.topicTypeList"
              :label="item.label"
              :key="item.id"
            >
              <el-col :span="6">
                <el-input-number v-model="item.value" min="1"></el-input-number>
              </el-col>
              <el-col :span="6">
                <el-button type="text" @click="RemoveTopic(item)"
                  >删除</el-button
                >
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="addTopic">添加题型</el-button>
          <el-button type="primary" @click="autoCombineConfirm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="题型选择"
      v-model="topicOpen"
      width="400px"
      append-to-body
    >
      <el-form
        :model="topicForm"
        :rules="topicRules"
        ref="topicRef"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="题型" prop="topicid">
              <el-select
                v-model="topicForm.topicid"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in topicTypeOption"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="topicSelectConfirm"
            >确 定</el-button
          >
          <el-button @click="topciCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Class">
import {
  getTestPaperList,
  deleteTestPaperByIds,
  autoTestPaper,
} from "@/api/core/testPaper";
import { getSubjectList } from "@/api/core/subject";
import { getTopicList } from "@/api/core/topic";
import { getSchoolClassList } from "@/api/core/class";
import {
  getCurrentInstance,
  reactive,
  ref,
  toRefs,
  watch,
  computed,
} from "vue";
import { parseTime } from "@/utils/ruoyi";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const router = useRouter();
const paperList = ref([]);
const knowledgeOptions = ref([]);
const subjectOptions = ref([]);
const classList = ref([]);
const studentList = ref([]);
const open = ref(false);
const addStudentOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const studentSelect = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const stuFlag = ref("");
const userStore = useUserStore();
const topicOpen = ref(false);
const topicTypeOption = ref([
  { id: 1, label: "单选" },
  { id: 2, label: "多选" },
  { id: 3, label: "判断" },
  { id: 5, label: "填空" },
  { id: 6, label: "简答" },
  { id: 7, label: "编程题" },
]);

const data = reactive({
  form: {
    id: null,
    subId: "",
    knowledgeId: [],
    classIdList: [],
    duration: 1,
    topicTypeList: [
      {
        value: 1,
        label: "单选题",
        id: 1,
      },
    ],
  },
  topicForm: {
    topicid: "",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    paperName: undefined,
  },
  currentRow: {},
  rules: {
    subId: [{ required: true, trigger: "change", message: "学科不能为空" }],
    classIdList: [
      { required: true, trigger: "change", message: "参试班级不能为空" },
    ],
    knowledgeId: [
      { required: true, trigger: "change", message: "知识点不能为空" },
    ],
  },
  topicRules: {
    topicid: [{ required: true, trigger: "blur", message: "题型不能为空" }],
  },
});
const isStudent = computed(() => useUserStore().isStudent);
const { queryParams, form, rules, currentRow, topicRules, topicForm } =
  toRefs(data);

/** 查询班级列表 */
function getList() {
  loading.value = true;
  getTestPaperList(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (res) => {
      loading.value = false;
      paperList.value = res.rows;
      total.value = res.total;
    }
  );
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const classIds = row.id || ids.value.toString();
  proxy.$modal
    .confirm("是否确认删除试卷？")
    .then(function () {
      return deleteTestPaperByIds(classIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 重置操作表单 */
function reset() {
  form.value = {
    id: null,
    subId: "",
    knowledgeId: [],
    classIdList: [],
    duration: 1,
  };
  proxy.resetForm("combineRef");
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 手动组卷操作 */
function handCombine() {
  // 跳转组卷路由
  router.push({ path: "/examination/create" });
}
// 编辑试卷
function handleEditTest(row) {
  console.log("dsdssdd", row);
  router.push({
    path: "/examination/create",
    query: { paperId: row.id },
  });
}
// 自动组卷
function handleAutoCombine() {
  open.value = true;
  getClassList();
}
function autoCombineConfirm() {
  proxy.$refs["combineRef"].validate((valid) => {
    if (valid) {
      if (form.value.topicTypeList.length > 0) {
        let paramObj = {
          subId: form.value.subId, // 学科id
          knowledgeIdList: form.value.knowledgeId, // 知识点ids
          topicTypeList: form.value.topicTypeList.map((item) => {
            return {
              topicTypeId: item.id, // 题目类型id
              topicTypeName: item.label, // 题目类型名称
              questionNum: item.value, // 题目数量
            };
          }),
          typeId: 1, // 试卷类型id
          duration: form.value.duration, // 建议时长
          classIdList: form.value.classIdList, // 关联的班级id列表
        };
        autoTestPaper(paramObj).then((res) => {
          console.log("自动组卷res", res);
          if (res.code == 200) {
            proxy.$modal.msgSuccess("组卷成功");
            handleQuery();
          }
          open.value = false;
        });
      } else {
        proxy.$modal.msgWarning("请至少添加一种题型");
      }
    }
  });
}
// 学科改变
function subjectChange(val) {
  form.value.knowledgeId = "";
  getTopicList({ subId: val }).then((res) => {
    knowledgeOptions.value = res.rows;
  });
}
// 首次请求学科列表
getSubjectList().then((res) => {
  subjectOptions.value = res.rows;
});
/** 查询班级列表 */
function getClassList() {
  getSchoolClassList().then((res) => {
    classList.value = res.rows;
  });
}
function addTopic() {
  topicForm.value = {
    topicid: "",
  };
  topicOpen.value = true;
}
// 删除
function RemoveTopic(item) {
  let index = form.value.topicTypeList.indexOf(item);
  if (index !== -1) {
    form.value.topicTypeList.splice(index, 1);
  }
}
function topicSelectConfirm() {
  console.log("topicForm.value.topicid", topicForm.value.topicid);
  proxy.$refs["topicRef"].validate((valid) => {
    if (valid) {
      // 题型是否重复
      if (
        form.value.topicTypeList.some((it) => it.id == topicForm.value.topicid)
      ) {
        proxy.$modal.msgWarning("已包含该题型，请求重新选择题型");
      } else {
        let findObj = topicTypeOption.value.find(
          (it) => it.id == topicForm.value.topicid
        );
        form.value.topicTypeList.push({
          id: findObj.id,
          label: findObj.label,
          value: 1,
        });
        topicOpen.value = false;
      }
    }
  });
}
function topciCancel() {
  topicOpen.value = false;
}
// 导出试卷
function handleDownload(row) {
  console.log("导出", row);
  proxy.download(`/core/export/export/${row.id}`, {}, `${row.paperName}.docx`);
}
getList();
</script>

<style scoped lang="scss"></style>
